<?php

/**
 * Description of friendplus
 *
 * @author Alexis
 */
class FriendPlus extends Facebook {
    
    public function init($reponse = false) {
        $code = isset($_REQUEST["code"]) && !empty($_REQUEST["code"]) ? $_REQUEST["code"] : null;
        if (empty($code)) {
            $url = urlencode(FB_URL_CANEVAS);
            if($reponse){
                $url = urlencode(FB_URL_CANEVAS_REPONSE);
                $_SESSION['rid'] = $_GET['rid'];
            }
            $_SESSION['state'] = md5(uniqid(rand(), TRUE)); //CSRF protection
            $dialog_url = "http://www.facebook.com/dialog/oauth?client_id="
                    . FB_APP_ID . "&redirect_uri=" . $url . "&state="
                    . $_SESSION['state'] . "&scope=read_friendlists,friends_birthday,friends_hometown,friends_about_me,friends_activities ,friends_education_history, friends_activities, friends_likes, , friends_interests, friends_work_history,publish_stream,publish_actions";

            echo("<script> top.location.href='" . $dialog_url . "'</script>");
        }
    }

    public function checkUser($current_user){
        $db_user = new Model_User();
        $result = $db_user->checkUserExist($current_user['id']);
        if(!$result){
            $me = $this->api('/me');
            @$formData = array('nom' =>$current_user['last_name'], 'prenom'=> $current_user['first_name'],'email'=> $current_user['email'],'id_facebook'=>$current_user['id'],'date_creation'=>date('Y-m-d H:i:s'));
             $result = $db_user->setUser($formData);
        }   
        
        return $result;
    }
    public function query($param) {

        $access_token = $this->getAccessToken();

        $query_url = 'https://graph.facebook.com/';
        $query_url .= $param;
        $query_url .= '?access_token=' . $access_token;

        $query_result = file_get_contents($query_url);
        $result = json_decode($query_result);

        return $result;
    }

    public function queryData($param) {

        $access_token = $this->getAccessToken();

        $query_url = 'https://graph.facebook.com/?';
        $query_url .= $param;
        $query_url .= '&access_token=' . $access_token;

        $query_result = file_get_contents($query_url);
        $result = json_decode($query_result);

        return $result;
    }

    public function getAllFriends() {
        return $this->query('me/friends');
    }

    public function getFriendById($fid) {
        return $this->query($fid);
    }

    public function getRandomFriendsId($max = 15) {
        $friendList = $this->getAllFriends();
        $friendList = $friendList->data;
        $myFriends = array();

        foreach ($friendList as $friend) {
            $myFriends[] = $friend->id;
        }

        shuffle($myFriends);
        $max = count($friendList) > $max ? $max : count($friendList);

        $result = array_slice($myFriends, 0, $max);

        return $result;
    }

    private function processData($friends_data, $filtre, $result = null) {
        if (!$result)
            $result = array();
        foreach ($friends_data as $data) {
            if (isset($data->$filtre) && (count($data->$filtre) > 0 || $data->$filtre != null)) {
                $value = $data->$filtre;
                if (count($value) > 0 && (is_object($value) || is_array($value))) {
                    if (isset($value->name) && $value->name != null) {
                        $value = $data->$filtre->name;
                        $value_id = $data->$filtre->id;
                    } else {
                        $random = rand(0, count($data->$filtre));
                        if (@isset($data->$filtre->data)) {
                            @$value = $data->$filtre->data[$random]->name;
                            @$value_id = $data->$filtre->data[$random]->id;
                        } else {
                            $array = $data->$filtre;
                            @$value = $array[$random]->name;
                            @$value_id = $array[$random]->id;
                        }
                        if (!$value)
                            continue;
                    }
                    if (!Utiles::multi_array_search($data->id, $result) && !Utiles::multi_array_search($value_id, $result))
                        $result[] = array('id' => $data->id, 'name' => $data->name,
                            'first_name' => $data->first_name, 'last_name' => $data->last_name,
                            'response' => $value, 'response_id' => $value_id);
                }elseif (is_string($data->$filtre)) {
                    if ($filtre == 'birthday')
                        $value = Utiles::formatDate($value);
                    $value_id = $data->id;
                    if (!Utiles::multi_array_search($data->id, $result) && !Utiles::multi_array_search($value_id, $result))
                        $result[] = array('id' => $data->id, 'name' => $data->name,
                            'first_name' => $data->first_name, 'last_name' => $data->last_name,
                            'response' => $value, 'response_id' => $value_id);
                }
            }

            if (count($result) == 4) { // sans le @ affiche une erreur...
                break;
            }
        }
        return $result;
    }

    function getFriendsList($qtype) {
        $fields = array('id', 'name', 'last_name', 'first_name', 'name');
        $filtre = $this->getFilter($qtype);
        $fields[] = $filtre;
        $friends = $this->getRandomFriendsId();
        $friends_ids = implode(',', $friends);
        $fields_list = implode(',', $fields);

        $friends_data = $this->queryData('ids=' . $friends_ids . '&fields=' . $fields_list);

        $result = $this->processData($friends_data, $filtre);

        $i = 0;
        while (count($result) < 4) {
            if ($i == 3)
                break;
            $friends = $this->getRandomFriendsId();
            $friends_ids = implode(',', $friends);
            $friends_data = $this->queryData('ids=' . $friends_ids . '&fields=' . $fields_list);
            $result = $this->processData($friends_data, $filtre, $result);
            $i++;
        }

        return $result;
    }

    public function getFilter($qtype) {
        switch ($qtype) {
            case '1': return 'hometown';
                break;
            case '2': return 'birthday';
                break;
            case '3': return 'movies';
                break;
            case '4': return 'music';
                break;
            case '5': return 'sports';
                break;
            case '6': return 'books';
                break;
            case '7': return 'games';
                break;
            case '8': return 'television';
                break;
            case '9': return 'interests';
                break;
            case '10': return 'favorite_teams';
                break;
        }
    }

    public function saveResponse($params) {
        $db_user = new Model_User();
        $db_score = new Model_Score();
        $db_user_response = new Model_User_Reponse();
        $db_user_question = new Model_User_Question();
        
        $qtype =  Utiles::getParam('qtype');
        $user = $db_user->getUserByFBId($this->getUser());
        
        $question_id = $db_user_question->setUserQuestion($qtype, $user['id_user']);
        if($db_score->checkScoreExist($user['id_user']) == false)
            $score_id = $db_score->setScore(array('id_user' => $user['id_user'], 'score' => 0));
        
        $i = $j = 0;
        $data = array();
        foreach($params as $key => $value){
            if(is_int($key)){
                $data[$i]['id_user_question'] = $question_id;
                $data[$i]['id_user_friend'] = $key;
                $response = explode('_', $value);
                $data[$i]['reponse'] = $response[0];
                $correct = $response[1];
                if($correct == 1)
                    $db_score->updateScore($user['id_user'],5);
                $data[$i]['id_reponse'] = $db_user_response->setUserReponse($data[$i]);
                $this->publishMessage($data[$i]);
                $data[$i]['correct'] = $correct;
                $i++;
            }
        }
        return $data;
    }

    public function getQuestion($ajax = false) {
        $connexion = new PDO_Mysql();
        $query = $connexion->query('SELECT t.id_type_question as type_question, question, type as type_name 
                                    FROM question q, type_question t
                                    WHERE q.id_type_question = t.id_type_question
                                    ORDER BY RAND()
                                    LIMIT 1');

        $result = $connexion->pfetchObj($query);
        $result->question = $ajax ? utf8_encode($result->question) : $result->question;

        return array('type_id' => $result->type_question,
            'question' => $result->question,
            'type_name' => $result->type_name);
    }
    
    public function getScoreStatistic(){
        $db_user = new Model_User();
        $db_score = new Model_Score();
        $db_user_response = new Model_User_Reponse();
        
        $user = $db_user->getUserByFBId($this->getUser());
        
        $data['score'] = $db_score->getUserScore($user['id_user']);
        $data['score_count'] = $db_score->getUserScore($user['id_user'],true);
        $data['total_reponse'] = $db_user_response->getCountReponse($user['id_user']);
        
        return $data;
        
    }
    
    public function publishMessage($data, $current_user = null){
        
        if(!$current_user){
            $db_user = new Model_User();
            $current_user = $db_user->getUserByFBId($this->getUser());
        }
        
        $message = array('message' => $current_user['prenom'] . " a répondu sur toi !",
                         'name' => 'Découvre la réponse ! ',
                         'link' => 'https://apps.facebook.com/friendsplus_/reponse.php?rid='.$data['id_user_friend'].'_' . $data['id_reponse'],
                         'description' => 'Découvre vite la réponse à la question que ' . $current_user['prenom'] . ' a répondu sur toi !' 
                        );
        $this->api('/'.$data['id_user_friend'].'/feed/','post',$message);
        
    }
}

?>
